package boot.service;

import boot.dao.ProductRepository;
import boot.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductService {
    @Autowired
    private ProductRepository repository;

    //增加产品
    public Product save(Product product) {
        return repository.save(product);
    }

    //根据id查找
    public Product getById(int id) {
        return repository.findById(id);
    }

    public List<Product> getByNameLike(String name) {
        return repository.findByNameLike(name);
    }

    public List<Product> getByCountBetween(int count1, int count2) {
        return repository.findByCountBetween(count1, count2);
    }

    public List<Product> getByType(String type) {
        return repository.findByType(type);
    }

    public List<Product> getByPriceBetween(float price, float price2) {
        return repository.findByPriceBetween(price, price2);
    }

    // 查询包含名字的产品, 每页size个数据, 返回第requestPage页
    public List<Product> getByNameContains(String name, int requestPage, int size) {
        Pageable pageable = PageRequest.of(requestPage, size);
        Page<Product> result = repository.findByNameContains(name, pageable);
        return result.getContent();
    }

    //按价格降序或升序放回分页
    public List<Product> getByNameContains(String name, int requestPage, int size, boolean flag) {
        Pageable pageable;
        if (flag)
           pageable = PageRequest.of(requestPage, size, Sort.by("price"));
        else
            pageable = PageRequest.of(requestPage, size, Sort.by(Sort.Direction.DESC, "price"));
        Page<Product> result = repository.findByNameContains(name, pageable);
        return result.getContent();
    }

    public List<Product> getWithJPQLByNameAndPrice(String name, float price) {
        return repository.findWithJPQLByNameAndPrice(name, price);
    }

    public void deleteProduct(int id) {
        repository.deleteById(id);
    }

    public void deleteAll() {
        repository.deleteAll();
    }
}
